<?php

/**
 *
 * @version $1.0$
 * @copyright 2011
 */
class Base_LocaleObject extends Erra_Fields_Base_Object {

    protected $_bFileExists = false;
    protected $_localizableSource = null;

    /**
     * locale::__construct()
     *
     * @param mixed $buildArgs
     */
    function __construct($objectId, $buildArgs = null) {
        parent::__construct($objectId, $buildArgs);
        if (strstr($buildArgs, '.php') == null && strstr($buildArgs, '.phtml') == null) {
            return null;
        }
        $this->_localizableSource = DOCUMENT_ROOT.'/'.$buildArgs;
        $this->setDescription(__('Editing file ') . '<i>' . $buildArgs . '</i>');

        $files = Erra_Core_File::spl_scanRecursiveDir(DOCUMENT_ROOT . '/application', '.php|.phtml');

        $fileList = array();
        $content_to_traduce = array();
        // We get all contents to traduce
        $realFilePath = $this->_localizableSource;
        foreach ($files as $a_file) {
            if (basename($this->_localizableSource) == basename($a_file)) {
                $this->_localizableSource = $a_file;
            }
        }
        if (file_exists($this->_localizableSource)) {
            $this->_bFileExists = true;

            $file_content = file_get_contents($this->_localizableSource);

            while (strlen($this->extract_string("__('", "')", $file_content)) > 2) {
                $extracted = $this->extract_string("__('", "')", $file_content);
                $file_content = str_replace("__('" . $extracted . "')", '', $file_content);
                if (strlen($extracted) > 0) {
                    $content_to_traduce[] = $extracted;
                }
            }
            while (strlen($this->extract_string('__("', '")', $file_content)) > 2) {
                $extracted = $this->extract_string('__("', '")', $file_content);
                $file_content = str_replace('__("' . $extracted . '")', '', $file_content);
                if (strlen($extracted) > 0) {
                    $content_to_traduce[] = $extracted;
                }
            }
            $langs = Erra_Core_Locale::getAvailableLangs();
            $langKeys = array_keys($langs);
            $default_lang = $langKeys[0];
            // On remplit notre variable locale avec les données obtenues
            foreach ($content_to_traduce as $iKey => $traduceElement) {
                $content = Erra_Fields_Text::create("traduce_" . $iKey)->setDescription(__('Translation'))->setSize(95)->_localize();
                $content->setDatabaseType('none');
                $contentKey = Erra_Fields_Hidden::create("key_traduce_" . $iKey);
                $contentKey->setDatabaseType('none');
                $contentKey->setRawData($traduceElement);
                foreach ($langKeys as $lang) {
                    $localizedFile = DOCUMENT_ROOT . "/application/L10n/translation.$lang.lang.php";

                    if (file_exists($localizedFile)) {
                        include($localizedFile);
                    }
                    // Try to get content from l10n array, else just set the key
                    if (isset($GLOBALS['__l10n'][$traduceElement])) {
                        $content->$lang->setRawData($GLOBALS['__l10n'][$traduceElement]);
                    }
                }
                $content->prepend('<i><strong>Key to translate</strong> : `' . $traduceElement . '`');
                $this->addFields($contentKey, $content);
            }
        }
        $this->setReadOnly(true);
    }

    public function __form($actionMethod) {
        if (!$this->_bFileExists) {
            return Erra_Utils_Tools::message('error', __('The file') . ' `' . $this->_localizableSource . '` ' . __('doesn\'t exists and can\'t be opened for edition'));
        }
        $this->prepend('<center><message id="saveLocale"/></center><br/>');
        return Erra_System_FormRenderer::editFieldAjax($this, $actionMethod);
    }

    /**
     * locale::_extract_string()
     *
     * @param mixed $start
     * @param mixed $end
     * @param mixed $string
     * @return
     */
    public static function _extract_string($start, $end, $string) {
        $string = " " . $string;
        $ini = strpos($string, $start);
        if ($ini == 0)
            return "";
        $ini += strlen($start);
        $len = strpos($string, $end, $ini) - $ini;
        return substr($string, $ini, $len);
    }

    /**
     * locale::get_localizable_file_list()
     *
     * @return
     */
    public static function get_localizable_file_list() {
        $files = Erra_Core_File::spl_scanRecursiveDir(DOCUMENT_ROOT . '/application', '.php|.phtml');
        $systemFiles = Erra_Core_File::spl_scanRecursiveDir(DOCUMENT_ROOT . '/library/Erra/System', '.php|.phtml');
        $files = array_merge($files, $systemFiles);
        $fileList = array();
        $content_to_traduce = array();
        // Get all contents to translate
        foreach ($files as $file) {
            if (strstr($file, '.php') !== false || strstr($file, '.phtml')) {
                $file_content = file_get_contents($file);

                if (strlen(self::_extract_string("__('", "')", $file_content)) > 2) {
                    $fileList[] = str_replace(DOCUMENT_ROOT, '', $file);
                }
            }
        }
        return $fileList;
    }

    public static function filepath_to_url($input) {
        $input = str_replace('/', '-sl-', $input);
        $input = str_replace(trim('\ '), '-asl-', $input);
        $input = str_replace('.', '-dot-', $input);
        $input = str_replace(':', '-dbdot-', $input);
        return $input;
    }

    public static function url_to_filepath($input) {
        $input = str_replace('-sl-', '/', $input);
        $input = str_replace('-asl-', trim('\ '), $input);
        $input = str_replace('-dot-', '.', $input);
        $input = str_replace('-dbdot-', ':', $input);
        return $input;
    }

    function extract_string($start, $end, $string) {
        $string = " " . $string;
        $ini = strpos($string, $start);
        if ($ini == 0)
            return "";
        $ini += strlen($start);
        $len = strpos($string, $end, $ini) - $ini;
        return substr($string, $ini, $len);
    }

}

?>